﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Extensions
{
    public static class MVCExtensions
    {
        public static ActionResult RedirectLocal(this Controller controller, string redirectUrl, Func<ActionResult> invalidUrlBehavior)
        {
            if (!string.IsNullOrWhiteSpace(redirectUrl) && controller.Url.IsLocalUrl(redirectUrl))
            {
                return new RedirectResult(redirectUrl);
            }
            return invalidUrlBehavior != null ? invalidUrlBehavior() : null;
        }

        public static ActionResult RedirectLocal(this Controller controller, string redirectUrl)
        {
            return RedirectLocal(controller, redirectUrl, (string)null);
        }

        public static ActionResult RedirectLocal(this Controller controller, string redirectUrl, string defaultUrl)
        {
            if (!string.IsNullOrWhiteSpace(redirectUrl)
                && controller.Url.IsLocalUrl(redirectUrl)
                && !redirectUrl.StartsWith("//")
                && !redirectUrl.StartsWith("/\\"))
            {
                return new RedirectResult(redirectUrl);
            }
            return new RedirectResult(defaultUrl ?? "~/");
        }
    }
}